package top.wyloop.intoeins.module.iam.initializer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import top.wyloop.intoeins.module.iam.model.consts.InitUserConst;
import top.wyloop.intoeins.module.iam.repository.UserRepository;
import top.wyloop.intoeins.util.PasswordUtil;

import java.util.Date;

/**
 * @author Wyatt6
 * @date 2025/2/1
 */
@Slf4j
@Component
@Order(3)
public class UserInitializer implements CommandLineRunner {
    @Autowired
    private UserRepository repository;

    @Override
    public void run(String... args) throws Exception {
        log.info("[[加载超级管理员用户初始数据]]");
        try {
            String salt = PasswordUtil.generateSalt();
            String encryptedPassword = PasswordUtil.encode(InitUserConst.SUPER_ADMIN_USER_ORIGINAL_PASSWORD, salt);

            repository.insert(
                    InitUserConst.SUPER_ADMIN_USER_ID,
                    InitUserConst.SUPER_ADMIN_USER_USERNAME,
                    encryptedPassword, salt,
                    1, new Date(), null);
            log.info("已加载：超级管理员用户 {}", InitUserConst.SUPER_ADMIN_USER_USERNAME);
        } catch (DataIntegrityViolationException e) {
            log.info("已存在：超级管理员用户 {}", InitUserConst.SUPER_ADMIN_USER_USERNAME);
        }
    }
}
